'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';

interface Stats {
  totalNews: number;
  publishedNews: number;
  totalViews: number;
  totalMembers: number;
  activeMembers: number;
}

interface RecentActivity {
  id: string;
  type: 'member' | 'project' | 'news' | 'application';
  title: string;
  description: string;
  timestamp: string;
  user: string;
}

export default function AdminDashboard() {
  const router = useRouter();
  
  const [stats, setStats] = useState<Stats>({
    totalNews: 0,
    publishedNews: 0,
    totalViews: 0,
    totalMembers: 0,
    activeMembers: 0
  });

  const [recentActivities, setRecentActivities] = useState<RecentActivity[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchStats = async () => {
      try {
        setLoading(true);
        setError(null);
        
        const response = await fetch('/api/admin/stats');
        
        if (response.ok) {
          const data = await response.json();
          
          if (data.success) {
            setStats(data.data.stats);
            setRecentActivities(data.data.recentActivities);
          } else {
            setError('API returned error: ' + (data.error || 'Unknown error'));
          }
        } else {
          setError(`HTTP error: ${response.status}`);
        }
      } catch (error) {
        setError('Network error: ' + (error instanceof Error ? error.message : 'Unknown error'));
      } finally {
        setLoading(false);
      }
    };

  useEffect(() => {
    fetchStats();
  }, []);

  const statCards = [
    {
      name: '新闻总数',
      value: stats.totalNews,
      color: 'blue',
      change: `${stats.publishedNews}已发布`,
      changeText: '已发布新闻',
      icon: '📰'
    },
    {
      name: '总阅读量',
      value: stats.totalViews.toLocaleString(),
      color: 'green',
      change: '累计访问',
      changeText: '新闻阅读',
      icon: '👁️'
    },
    {
      name: '发布状态',
      value: stats.totalNews > 0 ? `${Math.round((stats.publishedNews / stats.totalNews) * 100)}%` : '0%',
      color: 'purple',
      change: '发布率',
      changeText: '内容发布',
      icon: '📊'
    }
  ];

  const getActivityIcon = (type: string) => {
    switch (type) {
      case 'member':
        return '👥';
      case 'project':
        return '🔬';
      case 'news':
        return '📰';
      case 'application':
        return '📝';
      default:
        return '📊';
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        <span className="ml-3 text-gray-600">加载中...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="text-red-600 mb-2">❌ 加载错误</div>
          <p className="text-gray-600">{error}</p>
          <button 
            onClick={fetchStats}
            className="mt-4 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
          >
            重试
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Page Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">
            仪表板
          </h1>
          <p className="text-gray-600 mt-1">
            欢迎回来！这里是您的管理概览。
          </p>
        </div>
        <div className="text-sm text-gray-500">
          最后更新: {new Date().toLocaleString('zh-CN')}
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {statCards.map((stat, index) => (
          <div
            key={stat.name}
            className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 hover:shadow-md transition-shadow"
          >
            <div className="flex items-center">
              <div className={`
                p-3 rounded-lg text-2xl
                ${stat.color === 'blue' ? 'bg-blue-100' :
                  stat.color === 'purple' ? 'bg-purple-100' :
                  stat.color === 'green' ? 'bg-green-100' :
                  'bg-yellow-100'}
              `}>
                {stat.icon}
              </div>
            </div>
            <div className="mt-4">
              <h3 className="text-lg font-semibold text-gray-900">
                {stat.value}
              </h3>
              <p className="text-sm text-gray-600">{stat.name}</p>
            </div>
            <div className="mt-2 flex items-center text-xs">
              <span className="text-green-600 font-medium">{stat.change}</span>
              <span className="text-gray-500 ml-1">{stat.changeText}</span>
            </div>
          </div>
        ))}
      </div>

      {/* Content Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        {/* Recent Activities */}
        <div className="lg:col-span-2 bg-white rounded-xl shadow-sm border border-gray-200">
          <div className="p-4 border-b border-gray-200">
            <h2 className="text-lg font-semibold text-gray-900">最近活动</h2>
            <p className="text-sm text-gray-600 mt-1">系统中的最新动态</p>
          </div>
          <div className="p-4">
            <div className="space-y-3">
              {recentActivities.map((activity, index) => (
                <div key={activity.id} className="flex items-start space-x-3 p-3 rounded-lg hover:bg-gray-50 transition-colors">
                  <div className="flex-shrink-0 w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center text-sm">
                    {getActivityIcon(activity.type)}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-900">
                      {activity.title}
                    </p>
                    <p className="text-sm text-gray-500">
                      {activity.description}
                    </p>
                    <p className="text-xs text-gray-400 mt-1">
                      由 {activity.user} 操作 · {activity.timestamp}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Quick Actions */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200">
          <div className="p-4 border-b border-gray-200">
            <h2 className="text-lg font-semibold text-gray-900">快速操作</h2>
            <p className="text-sm text-gray-600 mt-1">常用功能入口</p>
          </div>
          <div className="p-4 space-y-2">
            <button 
              onClick={() => router.push('/admin/content')}
              className="w-full flex items-center justify-between p-3 text-left bg-purple-50 hover:bg-purple-100 rounded-lg transition-colors"
            >
              <div className="flex items-center space-x-3">
                <span className="text-lg">📰</span>
                <span className="text-sm font-medium text-purple-900">新闻管理</span>
              </div>
              <span className="text-purple-600">→</span>
            </button>
            
            <button 
              onClick={() => router.push('/admin/media')}
              className="w-full flex items-center justify-between p-3 text-left bg-green-50 hover:bg-green-100 rounded-lg transition-colors"
            >
              <div className="flex items-center space-x-3">
                <span className="text-lg">🖼️</span>
                <span className="text-sm font-medium text-green-900">媒体文件管理</span>
              </div>
              <span className="text-green-600">→</span>
            </button>

            <button 
              onClick={() => router.push('/admin/settings')}
              className="w-full flex items-center justify-between p-3 text-left bg-yellow-50 hover:bg-yellow-100 rounded-lg transition-colors"
            >
              <div className="flex items-center space-x-3">
                <span className="text-lg">⚙️</span>
                <span className="text-sm font-medium text-yellow-900">网站设置</span>
              </div>
              <span className="text-yellow-600">→</span>
            </button>
          </div>
        </div>
      </div>

      {/* News Management Preview */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
        <div className="flex items-center justify-between mb-3">
          <div>
            <h2 className="text-lg font-semibold text-gray-900">新闻管理</h2>
            <p className="text-sm text-gray-600 mt-1">管理网站展示的新闻动态</p>
          </div>
          <button
            onClick={() => router.push('/admin/content')}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm"
          >
            ➕ 发布新闻
          </button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          <div className="bg-blue-50 rounded-lg p-3">
            <div className="flex items-center">
              <div className="p-2 bg-blue-100 rounded-lg mr-3">
                <span className="text-lg">📰</span>
              </div>
              <div>
                <p className="text-sm font-medium text-blue-900">总新闻数</p>
                <p className="text-xl font-bold text-blue-700">{stats.totalNews}</p>
              </div>
            </div>
          </div>
          
          <div className="bg-green-50 rounded-lg p-3">
            <div className="flex items-center">
              <div className="p-2 bg-green-100 rounded-lg mr-3">
                <span className="text-lg">👁️</span>
              </div>
              <div>
                <p className="text-sm font-medium text-green-900">已发布</p>
                <p className="text-xl font-bold text-green-700">{stats.publishedNews}</p>
              </div>
            </div>
          </div>
          
          <div className="bg-purple-50 rounded-lg p-3">
            <div className="flex items-center">
              <div className="p-2 bg-purple-100 rounded-lg mr-3">
                <span className="text-lg">📊</span>
              </div>
              <div>
                <p className="text-sm font-medium text-purple-900">总阅读</p>
                <p className="text-xl font-bold text-purple-700">{stats.totalViews.toLocaleString()}</p>
              </div>
            </div>
          </div>
        </div>

        <div className="mt-3 flex items-center justify-between">
          <span className="text-sm text-gray-500">
            数据更新时间：{new Date().toLocaleString('zh-CN')}
          </span>
          <button
            onClick={() => router.push('/admin/content')}
            className="text-blue-600 hover:text-blue-800 text-sm font-medium"
          >
            查看全部新闻 →
          </button>
        </div>
      </div>

      {/* System Status */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
        <h2 className="text-lg font-semibold text-gray-900 mb-3">系统状态</h2>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          <div className="flex items-center justify-between p-3 bg-green-50 rounded-lg">
            <div>
              <p className="text-sm font-medium text-green-900">网站状态</p>
              <p className="text-xs text-green-600">正常运行</p>
            </div>
            <div className="w-3 h-3 bg-green-500 rounded-full"></div>
          </div>
          <div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
            <div>
              <p className="text-sm font-medium text-blue-900">数据库</p>
              <p className="text-xs text-blue-600">连接正常</p>
            </div>
            <div className="w-3 h-3 bg-blue-500 rounded-full"></div>
          </div>
          <div className="flex items-center justify-between p-3 bg-purple-50 rounded-lg">
            <div>
              <p className="text-sm font-medium text-purple-900">文件存储</p>
              <p className="text-xs text-purple-600">85% 已使用</p>
            </div>
            <div className="w-3 h-3 bg-purple-500 rounded-full"></div>
          </div>
        </div>
      </div>
    </div>
  );
}